﻿# ------------------------ #
# IIS Server Configuration #
# ------------------------ #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' IIS Server '$($script.type)' configuration ... " -NoNewLine $true
$userName = $subscription.virtualMachines.adminUserName
$password = $subscription.virtualMachines.password
$netBiosDomain = $subscription.virtualMachines.netBiosDomain
$uri = Get-AzureWinRMUri -ServiceName $virtualMachineService -Name $virtualMachineName
$credential = New-Object System.Management.Automation.PSCredential(($netBiosDomain + "\" + $userName), (ConvertTo-SecureString $password -AsPlainText -Force))
$session = New-PSSession -ComputerName $uri[0].DnsSafeHost -Credential $credential -Port (Get-VirtualMachineInstanceEndpointPort $subscription $virtualMachineName) -UseSSL
switch ($script.type)
{
	"SSL"
	{
		Invoke-Command -Session $session -ScriptBlock {
			param([string]$site, [string]$hostHeader, [string]$certificateName, [string]$certificateSNI)
	        # Setup HTTP.SYS SSL binding
            $thumbprint = (Get-Item Cert:\LocalMachine\My\* | ? {$_.FriendlyName -eq $certificateName}).Thumbprint
            if ($certificateSNI -eq $true)
            {
                if ((netsh http show sslcert hostnameport=$hostHeader`:443 | Out-String).IndexOf("Hostname:port") -ne -1) { netsh http delete sslcert hostnameport=$hostHeader`:443 | Out-Null }
	            netsh http add sslcert hostnameport=$hostHeader`:443 certstorename=MY certhash=$thumbprint appid=`{190c66be-a522-49ce-86b6-a20bfe724162`} | Out-Null
            }
            else
            {
                if ((netsh http show sslcert ipport=0.0.0.0:443 | Out-String).IndexOf("IP:port") -ne -1) { netsh http delete sslcert ipport=0.0.0.0:443 | Out-Null }
	            netsh http add sslcert ipport=0.0.0.0:443 certstorename=MY certhash=$thumbprint appid=`{190c66be-a522-49ce-86b6-a20bfe724162`} | Out-Null
            }
	        # Setup IIS SSL binding
            Get-WebBinding -Name $site | ? {$_.protocol -eq "https"} | Remove-WebBinding
            $sslFlags = "0"
            if ($certificateSNI -eq $true) { $sslFlags = "1" }
	        New-WebBinding -Name $site -Protocol https -Port 443 -IPAddress "*" -HostHeader $hostHeader -SslFlags $sslFlags
		} -ArgumentList $script.site, $script.hostHeader, $script.certificateName, $script.certificateSNI
	}
	default
	{
		throw "IIS Server type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."